#include "musicplayer.h"
#include "ui_musicplayer.h"
#include "terminalconsole.h"

musicPlayer::musicPlayer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::musicPlayer)
{
    ui->setupUi(this);
    ui->setupUi(this);
    //去窗口边框
    setWindowFlags(Qt::FramelessWindowHint | windowFlags());
    //把窗口背景设置为透明;
    setAttribute(Qt::WA_TranslucentBackground);
    //创建一个标准选项模型
    pModel=new QStandardItemModel(10,4,ui->tableView);
    //设置表头
    QStringList list_1 = QStringList()<<"歌名"<<"专辑"<<"歌手"<<"时长";
    pModel->setHorizontalHeaderLabels(list_1);
    //模型加入视图
    ui->tableView->setModel(pModel);
    //创建一个网络管理对象
    manager=new QNetworkAccessManager;
    //连接网络对象
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
    //连接按钮信号
   connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(on_pushButton_clicked()));
   //连接双击信号
   connect(ui->tableView,SIGNAL(doubleClicked(const QModelIndex )),this,SLOT(on_tableView_doubleClicked(const QModelIndex )));
   //创建一个媒体播放器
    player = new QMediaPlayer;
   //创建一个播放列表
    playList = new QMediaPlaylist;
    //将播放列表放入播放器中
    player->setPlaylist(playList);
    //连接按钮的槽函数
    connect(ui->toolButton,SIGNAL(clicked()),this,SLOT(on_toolButton_clicked()));
    connect(ui->toolButton_2,SIGNAL(clicked()),this,SLOT(on_toolButton_2_clicked()));
    connect(ui->toolButton_3,SIGNAL(clicked()),this,SLOT(on_toolButton_3_clicked()));
    //上一曲按钮 和 下一曲按钮
    connect(ui->upButton_2,SIGNAL(clicked(bool)),playList,SLOT(previous()));
    connect(ui->downButton_2,SIGNAL(clicked(bool)),playList,SLOT(next()));
    //播放音乐按钮
    connect(ui->playButton_2,SIGNAL(clicked()),this,SLOT(on_playButton_2_clicked()));
    //歌曲位置 歌曲总时长
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChangedSlot(qint64)));
//    // 绑定播放器的位置变化信号到更新播放进度函数
//    connect(player,&QMediaPlayer::positionChanged,this,&musicPlayer::updateDuration);
//    //连接按钮槽函数
//    connect(ui->hs_songtime_3,SIGNAL(valueChanged(int)),this,SLOT(hs_songtime_3_valueChanged(int)));
//    connect(ui->hs_songtime_3,SIGNAL(sliderPressed()),this,SLOT(on_hs_songtime_3_sliderPressed()));
    connect(ui->hs_songtime_3,SIGNAL(sliderReleased()),this,SLOT(on_hs_songtime_3_sliderReleased()));
}

void musicPlayer::replyFinished(QNetworkReply* reply)
{
    //QNetworkRequest::HttpStatusCodeAttribute网址返回的状态码
    qDebug()<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)<<endl;
    //状态为200表示连接成功
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<endl;
        //qDebug()<<QString(reply->readAll())<<endl;
        parseJson(reply->readAll());
    }
}

void musicPlayer::parseJson(QByteArray byteArray)
{
    QString songName;//歌名
    QString singerName;//歌手名
    QString albumName;//专辑名
    float duration;//时长

    //再次搜索时 清空列表
    playList->clear();

    QJsonDocument document = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    //判断JSON文档是否为一个对象
    if(true==document.isObject())
    {
        qDebug()<<"该文档是一个对象"<<endl;
        //如果是一个对象 那么接住它
        QJsonObject object_1 = document.object();
        //判断文档对象中是否 含有键值为result的字段
        if(object_1.contains("result") == false)
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        //如果存在result的字段 那么接住它
       QJsonValue value_1 = object_1.value("result");
        //将var值转换为一个对象
        QJsonObject resultObject = value_1.toObject();
        //判断resultObject是否 含有键值为songs的字段
        if(resultObject.contains("songs") == false)
        {
            qDebug()<<"JSON对象没有歌曲"<<endl;
            return;
        }
        QJsonValue value_2 = resultObject.value("songs");
        if(value_2.isArray()==false)
        {
            qDebug()<<"JSON对象不是一个数组"<<endl;
        }
        QJsonArray songsArr = value_2.toArray();
        //定义一个数组内的对象
        QJsonObject songsArrObject;
        //定义一个指向QJsonArray类数组成员的迭代器
        QJsonArray::iterator it;
        int i=0;
        for ( it = songsArr.begin();it !=songsArr.end() ;it++ )
        {
            songsArrObject = (*it).toObject();
            //如果数组成员对象 含有键值name字段
            if(songsArrObject.contains("name")==false)
            {
                qDebug()<<"该成员内无name"<<endl;
            }
            //打印songName
            QJsonValue value_songName = songsArrObject.value("name");
            songName = value_songName.toString();
            //打印singerName
            QJsonValue value_artists = songsArrObject.value("artists");
            QJsonArray artistsArr = value_artists.toArray();
            QJsonArray::iterator it_1;//定义一个指向artistsArr的迭代器
            for (it_1=artistsArr.begin();it_1!=artistsArr.end();it_1++)
            {
                QJsonObject artistsArrObject = (*it_1).toObject();
                QJsonValue artistsArrObjectName = artistsArrObject.value("name");
                singerName+=artistsArrObjectName.toString();
                singerName+=" ";
            }
            //打印专辑名
            QJsonValue valueAlbum = songsArrObject.value("album");
            QJsonObject AlbumObject = valueAlbum.toObject();
            QJsonValue valueName = AlbumObject.value("name");
            albumName = valueName.toString();
            //打印时长
            QJsonValue valueDuration= songsArrObject.value("duration");
            duration=valueDuration.toDouble()/1000/60;
            //打印歌id
            QJsonValue value_songId = songsArrObject.value("id");
            songId = value_songId.toDouble();
            //将歌ID放入播放列表
            playList->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(songId)));
            item_1 =new QStandardItem(songName);
            pModel->setItem(i,0,item_1);
            item_2 = new QStandardItem(albumName);
            pModel->setItem(i, 1, item_2);
            item_3 = new QStandardItem(singerName);
            pModel->setItem(i, 2, item_3);
            item_4= new QStandardItem(QString("%1").arg(duration));
            pModel->setItem(i, 3, item_4);
            singerName = "";//清空歌手名
            i++;

        }

    }
}

void musicPlayer::mouseMoveEvent(QMouseEvent *e)
{
    if (e->buttons() & Qt::LeftButton) {
               this->move(this->x() + e->globalX() - p.x(), this->y() + e->globalY() - p.y());
               p = e->globalPos();
           }
}

void musicPlayer::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
               p = e->globalPos();
    }
}

void musicPlayer::on_pushButton_clicked()
{
    manager->get(QNetworkRequest(QUrl(
    QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10")
    .arg(ui->lineEdit->text()))));
}



musicPlayer::~musicPlayer()
{
    delete ui;
    delete pModel;
    delete manager;
    delete item_1;
    delete item_2;
    delete item_3;
    delete item_4;
    delete playList;
    delete player;
}

void musicPlayer::on_tableView_doubleClicked(const QModelIndex &index)
{
    playList->setCurrentIndex(index.row());
    player->play();
    ui->playButton_2->setIcon(QIcon("g:/QtProjectImages/播放.png"));
}

void musicPlayer::on_toolButton_clicked()
{
    showMinimized();
}

void musicPlayer::on_toolButton_2_clicked()
{
    TerminalConsole * ter = new TerminalConsole;
    ter->show();
    player->stop();
    this->close();

}

void musicPlayer::on_toolButton_3_clicked()
{
    close();
}

void musicPlayer::on_downButton_2_clicked()
{
    playList->next();
    player->play();
}

void musicPlayer::on_playButton_2_clicked()
{
    if(player->state() == QMediaPlayer::PlayingState)
    {
        player->pause();    //暂停
        ui->playButton_2->setIcon(QIcon("g:/QtProjectImages/播放.png"));
    }
    else
    {
        player->play();     //播放
        ui->playButton_2->setIcon(QIcon("g:/QtProjectImages/暂停.png"));
    }
}

void musicPlayer::on_upButton_2_clicked()
{
    playList->previous();
    player->play();
}

void musicPlayer::positionChangedSlot(qint64 position)
{
    qDebug()<<position<<endl;
    ui->hs_songtime_3->setValue(position);
}

void musicPlayer::durationChangedSlot(qint64 duration)
{
    qDebug()<<"当前歌曲的总时长为"<<duration<<"毫秒"<<endl;
    //设置时间
    QTime time(0,duration/60000,qRound((duration%60000)/1000.0));
    ui->lb_time_3->setText(time.toString("mm:ss"));
    //设置滑块的总范围为歌曲的时长
    ui->hs_songtime_3->setRange(0,duration);
}

void musicPlayer::on_hs_songtime_3_sliderReleased()//拖动进度滑块
{
    qint64 var = ui->hs_songtime_3->value();//得到滑块当前值
    player->setPosition(var);//得到滑块当前值做为音乐播放的当前时间
}


